package com.kotlin.android.jetpack.image

import android.graphics.Bitmap
import android.widget.ImageView
import com.bumptech.glide.Priority
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.kotlin.android.api.config.Env
import com.kotlin.android.jetpack.module.GlideApp

/**
 * 创建者: zl
 * 创建时间: 2020/6/9 5:30 PM
 * 描述:图片加载管理器，先简单封装下，后续需要使用策略模式时再重新弄
 */


/**
 * 加载图片
 */
fun ImageView.loadImage(
    url: String,
    width: Int = 0,
    height: Int = 0,
    defaultImg: Int = R.drawable.default_image,
    useCache: Boolean = false,
    useProxy: Boolean = true
) {
    val options = getOptions(defaultImg, useCache)
    GlideApp.with(context)
        .applyDefaultRequestOptions(options)
        .load(getUrl(url, width, height, useProxy))
        .into(this)
}

fun ImageView.loadImageCallback(
    url: String,
    width: Int = 0,
    height: Int = 0,
    defaultImg: Int = R.drawable.default_image,
    useCache: Boolean = false,
    useProxy: Boolean = true,
    callBack: ImageViewCallBack?
) {
    val options = getOptions(defaultImg, useCache)
    val bitmapRequestBuilder =
        GlideApp.with(context).applyDefaultRequestOptions(options).asBitmap()

//    bitmapRequestBuilder.load(getUrl(url, width, height, useProxy))
//        .into(object : CustomTarget<Bitmap>() {
//            override fun onLoadCleared(placeholder: Drawable?) {
//            }
//
//            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                callBack?.setBitmap(resource)
//            }
//
//        })

    bitmapRequestBuilder.load(getUrl(url, width, height, useProxy))
        .into(object : BitmapImageViewTarget(this) {
            override fun setResource(resource: Bitmap?) {
                callBack?.setBitmap(resource)
            }
        })
}

/**
 * 拼接代理地址
 *
 * @param imgUrl
 * @param width
 * @param height
 * @return
 */
private fun getUrl(imgUrl: String, width: Int, height: Int, useProxy: Boolean): String {
    /**
     * 如果不需要使用代理，那就直接返回imgUrl
     */
    if (!useProxy) {
        return imgUrl
    }
    if (width == 0 || height == 0) {
        throw IllegalArgumentException("使用了图片代理，宽或高不能为0")
    }

    val url =
        "${Env.instance.imgProxyUrl}$imgUrl&width=$width&height=$height&quality=75&clipType=3&iswebp=true"
//    LogUtils.e("$url")
    return url
}

private fun getOptions(
    defaultImg: Int = R.drawable.default_image,
    useCache: Boolean = true
): RequestOptions {
    val options = RequestOptions().placeholder(defaultImg)
        .centerCrop()
        .dontTransform()
        .error(defaultImg)
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .priority(Priority.HIGH)
    if (useCache)
        options.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
    return options
}

interface ImageViewCallBack {
    fun setBitmap(bitmap: Bitmap?)
}